package com.xmy.cultivate.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.ChangeSchoolViews;
import com.xmy.cultivate.mapper.StudentGradeMapper;
import com.xmy.cultivate.service.IChangeSchoolContentService;
import com.xmy.cultivate.service.IChangeSchoolDetailService;
import com.xmy.cultivate.service.IChangeSchoolService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 转校 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2024-04-06
 */
@RestController
@RequestMapping("/api/changeSchool")
public class ChangeSchoolController extends BaseController {

    @Autowired
    @Lazy
    IChangeSchoolService iChangeSchoolService;

    @Autowired
    @Lazy
    IChangeSchoolDetailService iChangeSchoolDetailService;

    @Autowired
    @Lazy
    IChangeSchoolContentService iChangeSchoolContentService;

    @Autowired
    @Lazy
    IStudentService iStudentService;

    @Autowired
    @Lazy
    IOrderDetailService iOrderDetailService;

    @Autowired
    @Lazy
    StudentGradeMapper studentGradeMapper;

    @Autowired
    @Lazy
    private PlatformTransactionManager transactionManager;

    @Autowired
    @Lazy
    IMqPushService iMqPushService;

    @Autowired
    IOrderApplyService iOrderApplyService;

    @Autowired
    IGradeService iGradeService;

    @Autowired
    @Lazy
    IdWorker idWorker;

    /**
     * 按学员单独转校
     *
     * @param reMap
     * @return
     */
    @PostMapping("/changeSchoolByStudent")
    @Transactional
    public Result changeSchoolByStudent(@RequestBody Map reMap) {
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");
        String inSchoolId = (String) reMap.get("inSchoolId");
        String outSchoolId = (String) reMap.get("outSchoolId");
        String studentId = (String) reMap.get("studentId");
        String yearClassId = (String) reMap.get("yearClassId");

        try {

            Integer count = iOrderApplyService.getNotAffirmCount(Integer.parseInt(yearPart),Integer.parseInt(quarterNum),Long.parseLong(outSchoolId),Long.parseLong(studentId),subjectsId.toString());
            if (count > 0) {
                Student student = iStudentService.getById(studentId);
                return new Result(Code.ERROR,"", "转校失败，"+student.getName()+"”还有报名订单未确认，请先确认再转校");
            }
            ChangeSchool changeSchool = new ChangeSchool();
            changeSchool.setYearPart(Integer.valueOf(yearPart));
            changeSchool.setQuarterNum(Integer.valueOf(quarterNum));
            changeSchool.setType(1);
            changeSchool.setInSchoolId(Long.parseLong(inSchoolId));
            changeSchool.setCreatedId(this.adminId);
            iChangeSchoolService.save(changeSchool);

            Long id = changeSchool.getId();

            ChangeSchoolContent changeSchoolContent = new ChangeSchoolContent();
            changeSchoolContent.setChangeSchoolId(id);
            changeSchoolContent.setYearPart(Integer.valueOf(yearPart));
            changeSchoolContent.setQuarterNum(Integer.valueOf(quarterNum));
            changeSchoolContent.setSubjectsId(Long.parseLong(subjectsId));
            iChangeSchoolContentService.save(changeSchoolContent);

            //查找课时
            QueryWrapper<OrderDetail> wrapper = new QueryWrapper<>();
            wrapper.select("SUM( CASE WHEN STATUS <> 2 THEN all_course_count ELSE 0 END ) AS all_course_count,SUM( CASE WHEN STATUS <> 2 THEN use_course_count ELSE 0 END  ) AS use_course_count,SUM( CASE WHEN STATUS <> 2 THEN roll_out_house ELSE 0 END  ) AS roll_out_house,SUM( CASE WHEN STATUS <> 2 THEN out_house ELSE 0 END  ) AS out_house,SUM( CASE WHEN STATUS <> 2 THEN residue_course_count ELSE 0 END ) AS residue_course_count ");
            wrapper.eq("student_id", studentId);
            wrapper.eq("lesson_type", 1);
            wrapper.eq("school_id", outSchoolId);
            wrapper.eq("quarter_num", quarterNum);
            wrapper.eq("year_part", yearPart);
            wrapper.eq("subjects_id", subjectsId);
//            wrapper.ne("`status`", 2);
            wrapper.having("residue_course_count > 0 ");
            OrderDetail orderDetail = iOrderDetailService.getOne(wrapper);

            ChangeSchoolDetail changeSchoolDetail = new ChangeSchoolDetail();
            changeSchoolDetail.setId(idWorker.nextId());
            changeSchoolDetail.setChangeSchoolId(id);
            changeSchoolDetail.setType(1);
            changeSchoolDetail.setStudentId(Long.parseLong(studentId));
            changeSchoolDetail.setSubjectsId(Long.parseLong(subjectsId));
            changeSchoolDetail.setYearClassId(Integer.valueOf(yearClassId));
            changeSchoolDetail.setOutSchoolId(Long.parseLong(outSchoolId));
            changeSchoolDetail.setInSchoolId(Long.parseLong(inSchoolId));
            changeSchoolDetail.setYearPart(Integer.valueOf(yearPart));
            changeSchoolDetail.setQuarterNum(Integer.valueOf(quarterNum));
            changeSchoolDetail.setAllCourseCount(orderDetail.getAllCourseCount() - orderDetail.getRollOutHouse() - orderDetail.getOutHouse());
            changeSchoolDetail.setUseCourseCount(orderDetail.getUseCourseCount());
            changeSchoolDetail.setCreatedId(this.adminId);

            iChangeSchoolDetailService.save(changeSchoolDetail);
            iMqPushService.changeSchoolForStudent(changeSchoolDetail);

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.SAVE_ERROR, "", Code.SAVE_ERROR_MSG);
        }

        return new Result(Code.SAVE_OK, "", Code.SAVE_OK_MSG);
    }


    /**
     * 按学员批量转校
     *
     * @param reMap
     * @return
     */
    @PostMapping("/changeSchoolByStudentList")
    public Result changeSchoolByStudentList(@RequestBody Map reMap) {
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String inSchoolId = (String) reMap.get("inSchoolId");
        List<Object> studentList = (List<Object>) reMap.get("studentList");

        ChangeSchool changeSchool = new ChangeSchool();
        changeSchool.setYearPart(Integer.valueOf(yearPart));
        changeSchool.setQuarterNum(Integer.valueOf(quarterNum));
        changeSchool.setType(1);
        changeSchool.setInSchoolId(Long.parseLong(inSchoolId));
        changeSchool.setCreatedId(this.adminId);
        iChangeSchoolService.save(changeSchool);

        Long id = changeSchool.getId();

        StringBuilder errorStaffNames = new StringBuilder();
        Integer rightCount = 0;
        Integer errorCount = 0;
        StringBuilder sbNames = new StringBuilder();

        for (Object object : studentList) {
            String jsonObject = JSON.toJSONString(object);
            ChangeSchoolDetail changeSchoolDetail = JSONObject.parseObject(jsonObject, ChangeSchoolDetail.class);
            String names = iOrderApplyService.getNotAffirmStudentName(Integer.parseInt(yearPart),Integer.parseInt(quarterNum),changeSchoolDetail.getOutSchoolId(),changeSchoolDetail.getStudentId().toString(),changeSchoolDetail.getSubjectsId().toString());
            if (StringUtils.isNotBlank(names)){
                sbNames.append(names);
                sbNames.append(",");
            }
        }
        if (StringUtils.isNotBlank(sbNames.toString())){
            return new Result(Code.ERROR,"", "转校失败，"+sbNames+"”还有报名订单未确认，请先确认再转校");
        }

        for (Object object : studentList) {
            String jsonObject = JSON.toJSONString(object);
            ChangeSchoolDetail changeSchoolDetail = JSONObject.parseObject(jsonObject, ChangeSchoolDetail.class);
            try {

                ChangeSchoolContent changeSchoolContent = new ChangeSchoolContent();
                changeSchoolContent.setChangeSchoolId(id);
                changeSchoolContent.setYearPart(Integer.valueOf(yearPart));
                changeSchoolContent.setQuarterNum(Integer.valueOf(quarterNum));
                changeSchoolContent.setSubjectsId(changeSchoolDetail.getSubjectsId());
                iChangeSchoolContentService.save(changeSchoolContent);

                //查找课时
                QueryWrapper<OrderDetail> wrapper = new QueryWrapper<>();
                wrapper.select("SUM( CASE WHEN STATUS <> 2 THEN all_course_count ELSE 0 END ) AS all_course_count,SUM( CASE WHEN STATUS <> 2 THEN use_course_count ELSE 0 END  ) AS use_course_count,SUM( CASE WHEN STATUS <> 2 THEN roll_out_house ELSE 0 END  ) AS roll_out_house,SUM( CASE WHEN STATUS <> 2 THEN out_house ELSE 0 END  ) AS out_house,SUM( CASE WHEN STATUS <> 2 THEN residue_course_count ELSE 0 END ) AS residue_course_count ");
                wrapper.eq("student_id", changeSchoolDetail.getStudentId());
                wrapper.eq("lesson_type", 1);
                wrapper.eq("school_id", changeSchoolDetail.getOutSchoolId());
                wrapper.eq("quarter_num", quarterNum);
                wrapper.eq("year_part", yearPart);
                wrapper.eq("subjects_id", changeSchoolDetail.getSubjectsId());
                wrapper.having("residue_course_count > 0 ");
                OrderDetail orderDetail = iOrderDetailService.getOne(wrapper);

                changeSchoolDetail.setId(idWorker.nextId());
                changeSchoolDetail.setChangeSchoolId(id);
                changeSchoolDetail.setType(1);
                changeSchoolDetail.setStudentId(changeSchoolDetail.getStudentId());
                changeSchoolDetail.setSubjectsId(changeSchoolDetail.getSubjectsId());
                changeSchoolDetail.setYearClassId(changeSchoolDetail.getYearClassId());
                changeSchoolDetail.setOutSchoolId(changeSchoolDetail.getOutSchoolId());
                changeSchoolDetail.setInSchoolId(Long.parseLong(inSchoolId));
                changeSchoolDetail.setYearPart(Integer.valueOf(yearPart));
                changeSchoolDetail.setQuarterNum(Integer.valueOf(quarterNum));
                changeSchoolDetail.setCreatedId(this.adminId);
                changeSchoolDetail.setAllCourseCount(orderDetail.getAllCourseCount() - orderDetail.getRollOutHouse() - orderDetail.getOutHouse());
                changeSchoolDetail.setUseCourseCount(orderDetail.getUseCourseCount());

                iChangeSchoolDetailService.save(changeSchoolDetail);
                iMqPushService.changeSchoolForStudent(changeSchoolDetail);//推送到mq

                rightCount++;
            } catch (Exception e) {
                e.printStackTrace();
                errorStaffNames.append(iStudentService.getStudentName(changeSchoolDetail.getStudentId())).append(",");
                errorCount++;
            }
        }

        StringBuilder msgBd = new StringBuilder();
        msgBd.append("成功：").append(rightCount + "条数据");
        if (errorCount > 0) {
            msgBd.append(",");
            msgBd.append("失败：" + errorCount + "条数据");
            msgBd.append(",").append(errorStaffNames).append("转校失败");
        }

        return new Result(Code.SAVE_OK, "", msgBd.toString());
    }


    /**
     * 按科目单独转校
     *
     * @param reMap
     * @return
     */
    @PostMapping("/changeSchoolBySubjectsId")
    public Result changeSchoolBySubjectsId(@RequestBody Map reMap) {
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");
        String inSchoolId = (String) reMap.get("inSchoolId");
        String outSchoolId = (String) reMap.get("outSchoolId");
        String yearClassId = (String) reMap.get("yearClassId");

        StringBuilder errorStaffNames = new StringBuilder();
        Integer rightCount = 0;
        Integer errorCount = 0;

        ChangeSchool changeSchool = new ChangeSchool();
        changeSchool.setYearPart(Integer.valueOf(yearPart));
        changeSchool.setQuarterNum(Integer.valueOf(quarterNum));
        changeSchool.setType(1);
        changeSchool.setInSchoolId(Long.parseLong(inSchoolId));
        changeSchool.setCreatedId(this.adminId);
        iChangeSchoolService.save(changeSchool);

        Long id = changeSchool.getId();

        ChangeSchoolContent changeSchoolContent = new ChangeSchoolContent();
        changeSchoolContent.setChangeSchoolId(id);
        changeSchoolContent.setYearPart(Integer.valueOf(yearPart));
        changeSchoolContent.setQuarterNum(Integer.valueOf(quarterNum));
        changeSchoolContent.setSubjectsId(Long.parseLong(subjectsId));
        iChangeSchoolContentService.save(changeSchoolContent);

        // 根据选中的科目查询学生，并排除掉已经提交申请过的学员
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.select("student_id,SUM( CASE WHEN STATUS <> 2 THEN all_course_count ELSE 0 END ) AS all_course_count,SUM( CASE WHEN STATUS <> 2 THEN use_course_count ELSE 0 END  ) AS use_course_count,SUM( CASE WHEN STATUS <> 2 THEN roll_out_house ELSE 0 END  ) AS roll_out_house,SUM( CASE WHEN STATUS <> 2 THEN out_house ELSE 0 END  ) AS out_house,SUM( CASE WHEN STATUS <> 2 THEN residue_course_count ELSE 0 END ) AS residue_course_count ");
        wrapper.eq("lesson_type", 1);
        wrapper.eq("year_class_id", yearClassId);
        wrapper.eq("subjects_id", subjectsId);
        wrapper.eq("year_part", yearPart);
        wrapper.eq("quarter_num", quarterNum);
        wrapper.eq("school_id", outSchoolId);
        wrapper.notInSql("student_id", "SELECT change_school_detail.student_id FROM change_school_detail LEFT JOIN change_school ON change_school_detail.change_school_id = change_school.id WHERE change_school.`status` = 0 AND change_school_detail.subjects_id = order_detail.subjects_id AND change_school.year_part =" + yearPart + " AND change_school.quarter_num =" + quarterNum);
        wrapper.groupBy("student_id,subjects_id");
        wrapper.having("residue_course_count > 0 ");

        List<OrderDetail> orderDetails = iOrderDetailService.list(wrapper);

        if (CollectionUtils.isEmpty(orderDetails)) {
            return new Result(Code.ERROR, "", "该科目学员为空");
        }

        for (OrderDetail orderDetail : orderDetails) {
            try {
                ChangeSchoolDetail changeSchoolDetail = new ChangeSchoolDetail();
                changeSchoolDetail.setId(idWorker.nextId());
                changeSchoolDetail.setChangeSchoolId(id);
                changeSchoolDetail.setType(1);
                changeSchoolDetail.setStudentId(orderDetail.getStudentId());
                changeSchoolDetail.setSubjectsId(Long.parseLong(subjectsId));
                changeSchoolDetail.setYearClassId(Integer.valueOf(yearClassId));
                changeSchoolDetail.setOutSchoolId(Long.parseLong(outSchoolId));
                changeSchoolDetail.setInSchoolId(Long.parseLong(inSchoolId));
                changeSchoolDetail.setYearPart(Integer.valueOf(yearPart));
                changeSchoolDetail.setQuarterNum(Integer.valueOf(quarterNum));
                changeSchoolDetail.setAllCourseCount(orderDetail.getAllCourseCount() - orderDetail.getRollOutHouse() - orderDetail.getOutHouse());
                changeSchoolDetail.setUseCourseCount(orderDetail.getUseCourseCount());
                changeSchoolDetail.setCreatedId(this.adminId);

                iChangeSchoolDetailService.save(changeSchoolDetail);
                iMqPushService.changeSchoolForStudent(changeSchoolDetail);//推送到mq

                rightCount++;
            } catch (Exception e) {
                e.printStackTrace();
                errorStaffNames.append(iStudentService.getStudentName(orderDetail.getStudentId())).append(",");
                errorCount++;
            }
        }

        StringBuilder msgBd = new StringBuilder();
        msgBd.append("成功：").append(rightCount + "条数据");
        if (errorCount > 0) {
            msgBd.append(",");
            msgBd.append("失败：" + errorCount + "条数据");
            msgBd.append(",").append(errorStaffNames).append("转校失败");
        }

        return new Result(Code.SAVE_OK, "", msgBd.toString());
    }

    /**
     * 按科目批量转校
     *
     * @param reMap
     * @return
     */
    @PostMapping("/changeSchoolBySubjectsIdList")
    public Result changeSchoolBySubjectsIdList(@RequestBody Map reMap) {
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String inSchoolId = (String) reMap.get("inSchoolId");
        List<Object> subjectList = (List<Object>) reMap.get("subjectList");

        ChangeSchool changeSchool = new ChangeSchool();
        changeSchool.setYearPart(Integer.valueOf(yearPart));
        changeSchool.setQuarterNum(Integer.valueOf(quarterNum));
        changeSchool.setType(1);
        changeSchool.setInSchoolId(Long.parseLong(inSchoolId));
        changeSchool.setCreatedId(this.adminId);
        iChangeSchoolService.save(changeSchool);

        Long id = changeSchool.getId();

        StringBuilder errorStaffNames = new StringBuilder();
        Integer rightCount = 0;
        Integer errorCount = 0;

        for (Object object : subjectList) {
            String jsonObject = JSON.toJSONString(object);
            ChangeSchoolDetail schoolDetail = JSONObject.parseObject(jsonObject, ChangeSchoolDetail.class);

            ChangeSchoolContent changeSchoolContent = new ChangeSchoolContent();
            changeSchoolContent.setChangeSchoolId(id);
            changeSchoolContent.setYearPart(Integer.valueOf(yearPart));
            changeSchoolContent.setQuarterNum(Integer.valueOf(quarterNum));
            changeSchoolContent.setSubjectsId(schoolDetail.getSubjectsId());
            iChangeSchoolContentService.save(changeSchoolContent);

            // 根据选中的科目查询学生，并排除掉已经提交申请过的学员
            QueryWrapper wrapper = new QueryWrapper<>();
            wrapper.select("student_id,SUM( CASE WHEN STATUS <> 2 THEN all_course_count ELSE 0 END ) AS all_course_count,SUM( CASE WHEN STATUS <> 2 THEN use_course_count ELSE 0 END  ) AS use_course_count,SUM( CASE WHEN STATUS <> 2 THEN roll_out_house ELSE 0 END  ) AS roll_out_house,SUM( CASE WHEN STATUS <> 2 THEN out_house ELSE 0 END  ) AS out_house,SUM( CASE WHEN STATUS <> 2 THEN residue_course_count ELSE 0 END ) AS residue_course_count ");
            wrapper.eq("lesson_type", 1);
            wrapper.eq("year_class_id", schoolDetail.getYearClassId());
            wrapper.eq("subjects_id", schoolDetail.getSubjectsId());
            wrapper.eq("year_part", yearPart);
            wrapper.eq("quarter_num", quarterNum);
            wrapper.eq("deleted", 0);
            wrapper.eq("school_id", schoolDetail.getOutSchoolId());
            wrapper.gt("residue_course_count", 0);
            wrapper.notInSql("student_id", "SELECT change_school_detail.student_id FROM change_school_detail LEFT JOIN change_school ON change_school_detail.change_school_id = change_school.id WHERE change_school.`status` = 0 AND change_school_detail.subjects_id = order_detail.subjects_id AND change_school.year_part =" + yearPart + " AND change_school.quarter_num =" + quarterNum);
            wrapper.groupBy("student_id,subjects_id");
            wrapper.having("residue_course_count > 0 ");
            List<OrderDetail> orderDetails = iOrderDetailService.list(wrapper);

            for (OrderDetail orderDetail : orderDetails) {
                try {
                    ChangeSchoolDetail changeSchoolDetail = new ChangeSchoolDetail();
                    changeSchoolDetail.setId(idWorker.nextId());
                    changeSchoolDetail.setChangeSchoolId(id);
                    changeSchoolDetail.setType(1);
                    changeSchoolDetail.setStudentId(orderDetail.getStudentId());
                    changeSchoolDetail.setSubjectsId(schoolDetail.getSubjectsId());
                    changeSchoolDetail.setYearClassId(schoolDetail.getYearClassId());
                    changeSchoolDetail.setOutSchoolId(schoolDetail.getOutSchoolId());
                    changeSchoolDetail.setInSchoolId(Long.parseLong(inSchoolId));
                    changeSchoolDetail.setYearPart(Integer.valueOf(yearPart));
                    changeSchoolDetail.setQuarterNum(Integer.valueOf(quarterNum));
                    changeSchoolDetail.setAllCourseCount(orderDetail.getAllCourseCount() - orderDetail.getRollOutHouse() - orderDetail.getOutHouse());
                    changeSchoolDetail.setUseCourseCount(orderDetail.getUseCourseCount());
                    changeSchoolDetail.setCreatedId(this.adminId);

                    iChangeSchoolDetailService.save(changeSchoolDetail);
                    iMqPushService.changeSchoolForStudent(changeSchoolDetail);//推送到mq
                    rightCount++;
                } catch (Exception e) {
                    e.printStackTrace();
                    errorStaffNames.append(iStudentService.getStudentName(schoolDetail.getStudentId())).append(",");
                    errorCount++;
                }
            }
        }

        StringBuilder msgBd = new StringBuilder();
        msgBd.append("成功：").append(rightCount + "条数据");
        if (errorCount > 0) {
            msgBd.append(",");
            msgBd.append("失败：" + errorCount + "条数据");
            msgBd.append(",").append(errorStaffNames).append("转校失败");
        }

        return new Result(Code.SAVE_OK, "", msgBd.toString());
    }


    private Result saveChangeSchoolDate(Map<String, Object> reMap, int type) {//1老师，2校区老师，3校长，4校区
        if (type > 1) {
            QueryWrapper<ChangeSchoolContent> changeSchoolContentQueryWrapper = new QueryWrapper<>();
//            changeSchoolContentQueryWrapper.eq("year_part", reMap.get("yearPart"));
//            changeSchoolContentQueryWrapper.eq("quarter_num", reMap.get("quarterNum"));
            changeSchoolContentQueryWrapper.eq("deleted", 0);
            changeSchoolContentQueryWrapper.eq("grade_id", reMap.get("gradeId"));
            long count = iChangeSchoolContentService.count(changeSchoolContentQueryWrapper);
            if (count > 0L) {
                return new Result(Code.ERROR, "", "不可重复转校");
            }
        }
        ChangeSchool changeSchool = new ChangeSchool();
        if (reMap.get("yearPart") != null && !reMap.get("yearPart").toString().isEmpty()) {
            changeSchool.setYearPart(Integer.valueOf(reMap.get("yearPart").toString()));
        }
        if (reMap.get("quarterNum") != null && !reMap.get("quarterNum").toString().isEmpty()) {
            changeSchool.setQuarterNum(Integer.valueOf(reMap.get("quarterNum").toString()));
        }
        Date date = new Date();
        long getTime = date.getTime();
        int timestamp = (int) getTime;
        changeSchool.setReceiptNo("saveCSD" + timestamp);
        if (reMap.get("inSchoolId") != null && !reMap.get("inSchoolId").toString().isEmpty()) {
            changeSchool.setInSchoolId(Long.valueOf(reMap.get("inSchoolId").toString()));
        }
        if (reMap.get("isChangeTeacher") != null && !reMap.get("isChangeTeacher").toString().isEmpty()) {
            changeSchool.setIsChangeTeacher(Integer.valueOf(reMap.get("isChangeTeacher").toString()));
        }
        if (reMap.get("changeType") != null && !reMap.get("changeType").toString().isEmpty()) {
            changeSchool.setChangeType(Integer.valueOf(reMap.get("changeType").toString()));
        }
        if (reMap.get("startDate") != null && !reMap.get("startDate").toString().isEmpty()) {
            changeSchool.setStartDate(LocalDate.parse(reMap.get("startDate").toString()));
        }
        if (reMap.get("type") != null && !reMap.get("type").toString().isEmpty()) {
            changeSchool.setType(Integer.valueOf(reMap.get("type").toString()));
        }
        if (reMap.get("status") != null && !reMap.get("status").toString().isEmpty()) {
            changeSchool.setStatus(Integer.valueOf(reMap.get("status").toString()));
        } else {
            changeSchool.setStatus(0);
        }
        if (reMap.get("content") != null && !reMap.get("content").toString().isEmpty()) {
            changeSchool.setContent(reMap.get("content").toString());
        }
        changeSchool.setCreatedId(this.adminId);
        changeSchool.setDeleted(0);
        iChangeSchoolService.save(changeSchool);
        Long changeSchoolId = changeSchool.getId();
        if (changeSchoolId > 0L) {
            //写入说明
            ChangeSchoolContent changeSchoolContent = new ChangeSchoolContent();
            if (reMap.get("yearPart") != null && !reMap.get("yearPart").toString().isEmpty()) {
                changeSchoolContent.setYearPart(Integer.valueOf(reMap.get("yearPart").toString()));
            }
            if (reMap.get("quarterNum") != null && !reMap.get("quarterNum").toString().isEmpty()) {
                changeSchoolContent.setQuarterNum(Integer.valueOf(reMap.get("quarterNum").toString()));
            }
            changeSchoolContent.setChangeSchoolId(changeSchoolId);
            if (reMap.get("gradeId") != null && !reMap.get("gradeId").toString().isEmpty()) {
                changeSchoolContent.setGradeId(Long.valueOf(reMap.get("gradeId").toString()));
            }
            changeSchoolContent.setDeleted(0);
            iChangeSchoolContentService.save(changeSchoolContent);
            //拿出要录入的会员列表
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("grade_id", reMap.get("gradeId"));
            studentGradeQueryWrapper.eq("year_part", reMap.get("yearPart"));
            studentGradeQueryWrapper.eq("quarter_num", reMap.get("quarterNum"));
            studentGradeQueryWrapper.eq("lesson_type", 1);//1精品课，2智能课，3刷题班
            studentGradeQueryWrapper.eq("status", 1);//正常
            studentGradeQueryWrapper.in("reading_status", 0,1, 2,3,4, 5,6);//1在读，3退费，4停课，5结课
            studentGradeQueryWrapper.eq("deleted", 0);//0正常 1删除
            studentGradeQueryWrapper.groupBy("student_id");
            List<StudentGrade> studentList = studentGradeMapper.getGroupStudentList(studentGradeQueryWrapper);
            //写入会员
            for (StudentGrade studentGrade : studentList) {
                ChangeSchoolDetail changeSchoolDetail = new ChangeSchoolDetail();
                changeSchoolDetail.setId(idWorker.nextId());
                if (reMap.get("yearPart") != null && !reMap.get("yearPart").toString().isEmpty()) {
                    changeSchoolDetail.setYearPart(Integer.valueOf(reMap.get("yearPart").toString()));
                }
                if (reMap.get("quarterNum") != null && !reMap.get("quarterNum").toString().isEmpty()) {
                    changeSchoolDetail.setQuarterNum(Integer.valueOf(reMap.get("quarterNum").toString()));
                }
                changeSchoolDetail.setChangeSchoolId(changeSchoolId);
                changeSchoolDetail.setStudentId(studentGrade.getStudentId());
                changeSchoolDetail.setOutSchoolId(studentGrade.getSchoolId());
                changeSchoolDetail.setInSchoolId(changeSchool.getInSchoolId());
                if (reMap.get("changeTeacherId") != null && !reMap.get("changeTeacherId").toString().isEmpty()) {
                    changeSchoolDetail.setChangeTeacherId(Long.valueOf(reMap.get("changeTeacherId").toString()));
                }
                changeSchoolDetail.setSubjectsId(studentGrade.getSubjectsId());
                changeSchoolDetail.setYearClassId(studentGrade.getYearClassId());
                changeSchoolDetail.setType(Integer.valueOf(reMap.get("type").toString()));
                changeSchoolDetail.setCreatedId(this.adminId);
                changeSchoolDetail.setDeleted(0);
                iChangeSchoolDetailService.save(changeSchoolDetail);
                iMqPushService.changeSchoolForStudent(changeSchoolDetail);            }
        }
        return new Result(Code.OK, "", "添加成功");
    }

    @PostMapping("saveSchoolTransferGradeTeacher")
    @ApiOperation("转校->教师")
    public Result saveSchoolTransferGradeTeacher(@RequestBody Map<String, Object> reMap) {
        return batchOrSingleItem(reMap, 2);//1老师，2校区老师，3校长，4校区
    }

    @PostMapping("saveSchoolTransferGradeSchool")
    @ApiOperation("转校->校长")
    public Result saveSchoolTransferGradeSchool(@RequestBody Map<String, Object> reMap) {
        return batchOrSingleItem(reMap, 3);//1老师，2校区老师，3校长，4校区
    }

    private Result batchOrSingleItem(Map<String, Object> reMap, int type) {//1老师，2校区老师，3校长，4校区
        Result returnFor = null;
        StringBuilder sbNames = new StringBuilder();
        if (reMap.get("list") != null && !reMap.get("list").toString().isEmpty()) {
            //批量
            List<Object> rsList = (List<Object>) reMap.get("list");

            for (Object object : rsList) {
                String jsonObjectList = JSON.toJSONString(object);
                ChangeSchoolViews changeSchoolViews = JSONObject.parseObject(jsonObjectList, ChangeSchoolViews.class);
                Grade grade = iGradeService.getById(changeSchoolViews.getGradeId());
                String names = iOrderApplyService.getNotAffirmStudentNameForGradeId(changeSchoolViews.getYearPart(),changeSchoolViews.getQuarterNum(),grade.getSchoolId(),grade.getSubjectsId().toString(),grade.getId());
                if (StringUtils.isNotBlank(names)){
                    sbNames.append(names).append(",");
                }
            }
            if (StringUtils.isNotBlank(sbNames.toString())){
                return new Result(Code.ERROR,"", "转校失败，"+sbNames+"”还有报名订单未确认，请先确认再转校");
            }


            for (Object object : rsList) {
                String jsonObjectList = JSON.toJSONString(object);
                ChangeSchoolViews changeSchoolViews = JSONObject.parseObject(jsonObjectList, ChangeSchoolViews.class);
                Map<String, Object> reHashMap = new HashMap<>();
                reHashMap.put("yearPart", changeSchoolViews.getYearPart());
                reHashMap.put("quarterNum", changeSchoolViews.getQuarterNum());
                reHashMap.put("inSchoolId", changeSchoolViews.getInSchoolId());
                reHashMap.put("isChangeTeacher", changeSchoolViews.getIsChangeTeacher());
                reHashMap.put("changeType", changeSchoolViews.getChangeType());
                reHashMap.put("startDate", changeSchoolViews.getStartDate());
                reHashMap.put("type", changeSchoolViews.getType());
                reHashMap.put("status", changeSchoolViews.getStatus());
                reHashMap.put("content", changeSchoolViews.getContent());
                reHashMap.put("gradeId", changeSchoolViews.getGradeId());
                reHashMap.put("changeTeacherId", changeSchoolViews.getChangeTeacherId());
                returnFor = saveChangeSchoolDate(reHashMap, type);//1老师，2校区老师，3校长，4校区
            }
        } else {
            //单条
            Grade grade = iGradeService.getById(reMap.get("gradeId").toString());
            String names = iOrderApplyService.getNotAffirmStudentNameForGradeId(grade.getYearPart(),grade.getQuarterNum(),grade.getSchoolId(),grade.getSubjectsId().toString(),grade.getId());
            if (StringUtils.isNotBlank(names)){
                sbNames.append(names).append(",");
            }
            if (StringUtils.isNotBlank(sbNames.toString())){
                return new Result(Code.ERROR,"", "转校失败，"+sbNames+"”还有报名订单未确认，请先确认再转校");
            }
            return saveChangeSchoolDate(reMap, type);//1老师，2校区老师，3校长，4校区
        }
        return returnFor;
    }


    @GetMapping("/testPush")
    public Result testPush(@RequestParam("id") Long id){
        ChangeSchoolDetail changeSchoolDetail = iChangeSchoolDetailService.getById(id);
        iMqPushService.changeSchoolForStudent(changeSchoolDetail);//推送到mq
        return new Result(Code.OK,"","已添加到Mq");
    }

}
